package org.example.tool;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TextAlignment;
import org.example.LandEntity;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;


public class Base64ImageToPdf {
    public static void TransformBase64ToPdf(String base64Image, String outputPath, List<LandEntity> lands,String fontPath) throws IOException {

        // 2. 移除前缀，仅保留Base64编码部分
        String base64Data = base64Image;
        if (base64Image.contains(",")) {
            base64Data = base64Image.substring(base64Image.indexOf(",") + 1);
        }

        // 3. 清理Base64数据
        base64Data = base64Data.replaceAll("\\s", "");


        // 4. 解码Base64为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);

        // 5. 创建PDF文档（输出路径可自定义）
        PdfWriter writer = new PdfWriter(outputPath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document document = new Document(pdfDoc);

        // 6. 将字节数组转换为iText可识别的图片对象
        ImageData imageData = ImageDataFactory.create(imageBytes);
        Image image = new Image(imageData);

        // 可选：设置图片大小（按比例缩放，避免变形）
        float pageWidth = pdfDoc.getDefaultPageSize().getWidth() - document.getLeftMargin() - document.getRightMargin();
        image.scaleToFit(pageWidth, Float.MAX_VALUE);
//            image.scaleToFit(400, 400); // 最大宽度400，最大高度400

        // 7. 将图片添加到PDF
        document.add(image);
        // 在第二页插入表格
        // 8. 添加新页用于表格
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
// 9. 创建6列表格
// 假设字体文件放在 resources/fonts/simsun.ttf
//        PdfFont font = PdfFontFactory.createFont(fontPath, "Identity-H");
        PdfFont font = loadChineseFont();
        Table table = new Table(6).useAllAvailableWidth();
        table.setFont(font);
        table.setTextAlignment(TextAlignment.CENTER);
        // 添加表头 - 白色字体，灰色背景
        table.addHeaderCell(createHeaderCell("农户姓名"));
        table.addHeaderCell(createHeaderCell("地块编码"));
        table.addHeaderCell(createHeaderCell("投保面积"));
        table.addHeaderCell(createHeaderCell("农户姓名"));
        table.addHeaderCell(createHeaderCell("地块编码"));
        table.addHeaderCell(createHeaderCell("投保面积"));
        // 遍历lands列表填充表格数据
        for (LandEntity land : lands) {
            table.addCell(createParagraph(land.getNhxm()));
            table.addCell(createParagraph(land.getNhqqdm()));
            table.addCell(createParagraph(String.valueOf(land.getTbmj())));
        }

        // 10. 将表格添加到文档
        document.add(table);
        // 8. 关闭文档
        document.close();


    }


    public static Paragraph createParagraph(String text) {
        Paragraph paragraph = new Paragraph(text);
        paragraph.setTextAlignment(TextAlignment.CENTER);
        return paragraph;
    }
    public static Cell createHeaderCell(String text) {
        Cell cell= new Cell().add(createParagraph(text).setFontColor(ColorConstants.WHITE));
        cell.setBackgroundColor(ColorConstants.GRAY);
        return cell;
    }


    private static PdfFont loadChineseFont() {
        try {
            // 方法1: 从资源文件加载
            InputStream fontStream = Base64ImageToPdf.class.getResourceAsStream("/fonts/simsun.ttf");
            if (fontStream != null) {
                byte[] fontBytes = readAllBytes(fontStream);
                fontStream.close();
                return PdfFontFactory.createFont(fontBytes, "Identity-H");
            }
            throw new RuntimeException("Unable to load Chinese font");
        } catch (Exception e) {
            System.err.println("Failed to load font from resource: " + e.getMessage());
            throw new RuntimeException("Unable to load Chinese font", e);
        }

    }

    // 添加辅助方法来读取所有字节
    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        return buffer.toByteArray();
    }
}
